package com.joysuch.wwyt.dzhapi.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.joysuch.wwyt.api.basedata.service.BpDepartSyncService;
import com.joysuch.wwyt.api.basedata.service.BpJobSyncService;
import com.joysuch.wwyt.bp.entity.*;
import com.joysuch.wwyt.bp.entity.contractor.BpContractorStaff;
import com.joysuch.wwyt.bp.enums.DataStateTypes;
import com.joysuch.wwyt.bp.enums.DepartType;
import com.joysuch.wwyt.bp.repository.*;
import com.joysuch.wwyt.bp.service.BpDepartService;
import com.joysuch.wwyt.bp.service.BpJobService;
import com.joysuch.wwyt.core.common.util.DateTimeUtil;
import com.joysuch.wwyt.core.constant.Constants;
import com.joysuch.wwyt.core.entity.*;
import com.joysuch.wwyt.core.enums.BaseConfigCodes;
import com.joysuch.wwyt.core.enums.Status;
import com.joysuch.wwyt.core.repository.BaseLoginAccountDao;
import com.joysuch.wwyt.core.repository.BaseRoleDao;
import com.joysuch.wwyt.core.repository.BaseRoleUserLoginRoleDao;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.service.BaseConfigService;
import com.joysuch.wwyt.core.service.BaseLoginAccountService;
import com.joysuch.wwyt.core.service.BaseRoleDataAuthService;
import com.joysuch.wwyt.dzhapi.bean.*;
import com.joysuch.wwyt.dzhapi.dto.BuildDataDto;
import com.joysuch.wwyt.dzhapi.exception.ApiException;
import com.joysuch.wwyt.dzhapi.mapper.*;
import com.joysuch.wwyt.dzhapi.req.ApiBaseUserAddReq;
import com.joysuch.wwyt.dzhapi.req.ApiBaseUserUpdateReq;
import com.joysuch.wwyt.dzhapi.req.ApiBaseUserUpdateWorkCompanyReq;
import com.joysuch.wwyt.dzhapi.service.ApiBaseUserService;
import com.joysuch.wwyt.dzhapi.service.ApiBpEnterpriseInfoService;
import com.joysuch.wwyt.dzhapi.vo.ApiResultData;
import com.joysuch.wwyt.monitoringcenter.service.LocateServerService;
import com.joysuch.wwyt.util.SnowFlakeUtil;
import com.joysuch.wwyt.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.transaction.Transactional;
import java.util.*;

/**
 * @author: JamesZY
 * @date: 2021/9/16
 * @description:
 */
@Slf4j
@Service
public class ApiBaseUserServiceImpl implements ApiBaseUserService {
    @Value("${wwyt.biz.user.account.forceSyncCodeAsLoginAccount}")
    private boolean forceSyncCodeAsLoginAccount;
    @Value("${wwyt.biz.user.account.defaultPassword}")

    private String defaultPassword;
    @Autowired
    private BaseUserDao baseUserDao;
    @Autowired
    private BpEnterpriseInfoDao infoDao;
    @Autowired
    private BpJobDao jobDao;
    @Autowired
    private BpJobSyncService jobSyncService;
    @Autowired
    private BpDepartSyncService departSyncService;
    @Autowired
    private BpDepartDao departDao;
    @Autowired
    private BpContractorStaffDao bpContractorStaffDao;
    @Autowired
    private BaseRoleDao baseRoleDao;
    @Autowired
    private BaseRoleUserLoginRoleDao baseRoleUserLoginRoleDao;
    @Autowired
    private LocateServerService locateServerService;
    @Autowired
    private BaseConfigService baseConfigService;
    @Autowired
    private BaseLoginAccountService baseLoginAccountService;
    @Autowired
    private BaseLoginAccountDao baseLoginAccountDao;
    @Autowired
    private BpJobService jobService;
    @Autowired
    private BpDepartService departService;
    @Autowired
    private BaseRoleDataAuthService dataAuthService;
    @Autowired
    private ApiBaseUserMapper apiBaseUserMapper;
    @Autowired
    private ApiBaseConfigMapper configMapper;
    @Autowired
    private ApiBpJobMapper bpJobMapper;
    @Autowired
    private ApiBpDepartMapper bpDepartMapper;
    @Autowired
    private ApiBpEnterpriseInfoMapper infoMapper;
    @Autowired
    private ApiBaseLoginAccountMapper baseLoginAccountMapper;
    @Autowired
    private ApiBpContractorStaffMapper contractorStaffMapper;

    @Override
    @Transactional(rollbackOn = {Exception.class})
    public List<ApiResultData> batchAdd(List<ApiBaseUserAddReq> data, BuildDataDto buildDataDto) {
        List<ApiResultData> result = Lists.newArrayList();
        data.forEach(u -> {
                    ApiResultData resultData = new ApiResultData();
                    if (StringUtil.isEmpty(u.getRealName())) {
                        resultData.setSyncStatus(Status.ERROR_STATUS);
                        resultData.setName(u.getRealName());
                        resultData.setMsg("人员姓名不能为空");
                        resultData.setUserCode(u.getCode());
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.isEmpty(u.getDepart())) {
                        resultData.setSyncStatus(Status.ERROR_STATUS);
                        resultData.setName(u.getRealName());
                        resultData.setMsg("部门名称不能为空");
                        resultData.setUserCode(u.getCode());
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.isEmpty(u.getJob())) {
                        resultData.setSyncStatus(Status.ERROR_STATUS);
                        resultData.setName(u.getRealName());
                        resultData.setMsg("岗位名称不能为空");
                        resultData.setUserCode(u.getCode());
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.isEmpty(u.getCode())) {
                        resultData.setSyncStatus(Status.ERROR_STATUS);
                        resultData.setName(u.getRealName());
                        resultData.setMsg("工号不能为空");
                        resultData.setUserCode(u.getCode());
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.isEmpty(u.getWorkCompany())) {
                        resultData.setSyncStatus(Status.ERROR_STATUS);
                        resultData.setName(u.getRealName());
                        resultData.setMsg("工作单位不能为空");
                        resultData.setUserCode(u.getCode());
                        result.add(resultData);
                        return;
                    }
                    if (ObjectUtil.isEmpty(u.getRole())) {
                        resultData.setSyncStatus(Status.ERROR_STATUS);
                        resultData.setName(u.getRealName());
                        resultData.setMsg("身份不能为空");
                        resultData.setUserCode(u.getCode());
                        result.add(resultData);
                        return;
                    }
//                    if (ObjectUtil.isEmpty(u.getSn())) {
//                        resultData.setSyncStatus(Status.ERROR_STATUS);
//                        resultData.setName(u.getRealName());
//                        resultData.setMsg("定位卡号不能为空");
//                        resultData.setUserCode(u.getCode());
//                        result.add(resultData);
//                        return;
//                    }
                    if (u.getRealName().length() > 64) {
                        resultData.setSyncStatus(Status.ERROR_STATUS);
                        resultData.setName(u.getRealName());
                        resultData.setMsg("姓名长度不能超过64字符");
                        resultData.setUserCode(u.getCode());
                        result.add(resultData);
                        return;
                    }
                    if (u.getDepart().length() > 64) {
                        resultData.setSyncStatus(Status.ERROR_STATUS);
                        resultData.setName(u.getRealName());
                        resultData.setMsg("部门长度不能超过64字符");
                        resultData.setUserCode(u.getCode());
                        result.add(resultData);
                        return;
                    }
                    if (u.getJob().length() > 64) {
                        resultData.setSyncStatus(Status.ERROR_STATUS);
                        resultData.setName(u.getRealName());
                        resultData.setMsg("岗位长度不能超过64字符");
                        resultData.setUserCode(u.getCode());
                        result.add(resultData);
                        return;
                    }
                    if (u.getCode().length() > 10) {
                        resultData.setSyncStatus(Status.ERROR_STATUS);
                        resultData.setName(u.getRealName());
                        resultData.setMsg("工号长度不能超过10字符");
                        resultData.setUserCode(u.getCode());
                        result.add(resultData);
                        return;
                    }
                    if (u.getWorkCompany().length() > 64) {
                        resultData.setSyncStatus(Status.ERROR_STATUS);
                        resultData.setName(u.getRealName());
                        resultData.setMsg("工作单位长度不能超过64字符");
                        resultData.setUserCode(u.getCode());
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.notEmpty(u.getSn()) && u.getSn().length() > 64) {
                        resultData.setSyncStatus(Status.ERROR_STATUS);
                        resultData.setName(u.getRealName());
                        resultData.setMsg("定位卡号长度不能超过64字符");
                        resultData.setUserCode(u.getCode());
                        result.add(resultData);
                        return;
                    }
                    if (StringUtil.notEmpty(u.getSn()) && apiBaseUserMapper.countBySn(u.getSn(), buildDataDto.getTenentId(), buildDataDto.getOrgCode()) > 0) {
                        resultData.setSyncStatus(Status.ERROR_STATUS);
                        resultData.setName(u.getRealName());
                        resultData.setMsg("sn已存在");
                        resultData.setUserCode(u.getCode());
                        result.add(resultData);
                        return;
                    }
                    resultData.setName(u.getRealName());
                    resultData.setUserCode(u.getCode());
                    resultData.setSyncStatus(Status.SUCCESS_STATUS);
                    if (u.getCode() != null && apiBaseUserMapper.countOfCode(u.getCode(), buildDataDto.getTenentId(), buildDataDto.getOrgCode()) > 0) {
                        resultData.setSyncStatus(Status.ERROR_STATUS);
                        resultData.setMsg("工号已存在");
                        resultData.setUserCode(u.getCode());
                        result.add(resultData);
                        return;
                    }
                    if (apiBaseUserMapper.countByName(u.getRealName(), buildDataDto.getTenentId(), buildDataDto.getOrgCode()) > 0) {
                        resultData.setSyncStatus(Status.ERROR_STATUS);
                        resultData.setMsg("姓名已存在");
                        resultData.setUserCode(u.getCode());
                        result.add(resultData);
                        return;
                    }
                    BaseUser b = new BaseUser();
                    BeanUtils.copyProperties(u, b);
                    b.setUniqueId(SnowFlakeUtil.getUserId());
                    if (StringUtil.notEmpty(u.getWorkCompany())) {
                        ApiBpEnterpriseInfoBean info = infoMapper.findByCompanyName(u.getWorkCompany(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
                        if (info == null) {
                            resultData.setMsg("工作单位不存在");
                            resultData.setSyncStatus(Status.ERROR_STATUS);
                            resultData.setUserCode(u.getCode());
                            result.add(resultData);
                            return;
                        }
                        b.setWorkCompanyId(info.getId());
                    }
//                    try {
//                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                        if (!org.springframework.util.StringUtils.isEmpty(u.getBirthday())) {
//                            b.setBirthday(sdf.parse(u.getBirthday()));
//                        }
//                        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
//                        if (u.getJoinWorkDate() != null && StringUtils.isNotBlank(u.getJoinWorkDate())) {
//                            b.setJoinWorkDate(fmt.parse(u.getJoinWorkDate()));
//                        }
//                        if (u.getEnterDate() != null && StringUtils.isNotBlank(u.getEnterDate())) {
//                            b.setEnterDate(fmt.parse(u.getEnterDate()));
//                        }
//                    } catch (Exception e) {
//                        log.error(e.getMessage(), e);
//                        resultData.setUniqueId(u.getUniqueId());
//                        resultData.setName(u.getRealName());
//                        resultData.setMsg("日期格式转换错误");
//                        result.add(resultData);
//                        return;
//                    }
                    BpJob job = new BpJob();
//                    BpJob jobSave = null;
                    boolean jobSync = false;
                    ApiBpJobBean bean = new ApiBpJobBean();
                    if (StringUtil.notEmpty(u.getJob())) {
                        ApiBpJobBean jobBean = bpJobMapper.findByNameAndCurrentCompany(u.getJob(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
//                        BeanUtils.copyProperties(jobBean, job);
                        if (ObjectUtil.isEmpty(jobBean)) {
                            BpJob jobEntity = BpJob.builder().name(u.getJob()).staffCount(0).createBy(-1L).createTime(new Date())
                                    .updateBy(-1L).updateTime(new Date()).uniqueId(SnowFlakeUtil.getJobId())
                                    .orgCode(buildDataDto.getOrgCode()).tenentId(buildDataDto.getTenentId()).build();
                            jobSync = jobSyncService.syncApiJob(jobEntity, buildDataDto);
                            if (jobSync) {
                                jobEntity.setLocateSync(true);
                            } else {
                                jobEntity.setLocateSync(false);
                            }
                            BeanUtils.copyProperties(jobEntity, bean);
                            bpJobMapper.insert(bean);
//                            jobSave = jobDao.save(jobEntity);
                        } else {
                            BeanUtils.copyProperties(jobBean, job);
                            jobSync = jobSyncService.syncApiJob(job, buildDataDto);
                            if (jobSync) {
                                job.setLocateSync(true);
                            } else {
                                job.setLocateSync(false);
                            }
                        }
                        b.setJob(ObjectUtil.isEmpty(bean.getId()) ? job.getId() : bean.getId());
                    }
                    BpDepart depart = new BpDepart();
                    BpDepart departSave = null;
                    boolean departSync = false;
                    ApiBpDepartBean departBean = new ApiBpDepartBean();
                    ApiBpDepartBean departSaveBean = new ApiBpDepartBean();
                    BpDepart fatherDepart = new BpDepart();
                    if (StringUtil.notEmpty(u.getDepart())) {
                        ApiBpDepartBean fatherDepartBean = bpDepartMapper.getFatherDepart(buildDataDto.getOrgCode(), buildDataDto.getTenentId());
                        Integer no = fatherDepartBean.getChildNo();
                        if (no == null) {
                            no = 1;
                        }
                        departBean = bpDepartMapper.findFirstByNameAndCurrentCompany(u.getDepart(), buildDataDto.getOrgCode(), buildDataDto.getTenentId());
                        if (ObjectUtil.isEmpty(departBean)) {
                            if (fatherDepartBean == null) {
                                //出现异常删除定位系统已保存的数据
                                if (jobSync) {
                                    jobService.apiDelete(bean.getId(), buildDataDto);
                                } else {
                                    jobService.apiDelete(job.getId(), buildDataDto);
                                }
                                resultData.setSyncStatus(Status.ERROR_STATUS);
                                resultData.setMsg("顶级部门不存在");
                                resultData.setUserCode(u.getCode());
                                result.add(resultData);
                                return;
                            }
                            BeanUtils.copyProperties(fatherDepartBean, fatherDepart);
                            BpDepart departEntity = BpDepart.builder().name(u.getDepart()).parentId(fatherDepart.getId())
                                    .childNo(0).type(DepartType.DEPART.getId()).uniqueId(SnowFlakeUtil.getDepartId()).createBy(-1L)
                                    .createTime(DateTimeUtil.date2LocalDateTime(new Date())).updateBy(-1L).updateTime(DateTimeUtil.date2LocalDateTime(new Date()))
                                    .tenentId(buildDataDto.getTenentId()).orgCode(buildDataDto.getOrgCode())
                                    .code(fatherDepart.getCode() + "-" + StringUtils.leftPad(no + "", 3, '0')).build();
                            // 调用同步接口，同步部门信息到人员在岗在位
                            departSync = departSyncService.syncApiDepart(departEntity, fatherDepart, buildDataDto);
                            if (departSync) {
                                departEntity.setLocateSync(true);
                            } else {
                                departEntity.setLocateSync(false);
                            }
                            BeanUtils.copyProperties(departEntity, departSaveBean);
                            bpDepartMapper.insert(departSaveBean);
//                            departSave = departDao.save(departEntity);
                            fatherDepartBean.setChildNo(no + 1);
                            bpDepartMapper.updateById(fatherDepartBean);
//                            departDao.save(fatherDepart);
                            dataAuthService.initAllRoleDepartCache();
                        } else {
                            BeanUtils.copyProperties(departBean, depart);
                            if (fatherDepartBean == null) {
                                //出现异常删除定位系统已保存的数据
                                if (jobSync) {
                                    jobService.delete(bean.getId());
                                } else {
                                    jobService.delete(job.getId());
                                }
                                resultData.setSyncStatus(Status.ERROR_STATUS);
                                resultData.setMsg("顶级部门不存在");
                                resultData.setUserCode(u.getCode());
                                result.add(resultData);
                                return;
                            }
                            BeanUtils.copyProperties(fatherDepartBean, fatherDepart);
                            departSync = departSyncService.syncApiDepart(depart, fatherDepart, buildDataDto);
                            if (departSync) {
                                depart.setLocateSync(true);
                            } else {
                                depart.setLocateSync(false);
                            }
                            dataAuthService.initAllRoleDepartCache();
                        }
                        b.setDepartId(ObjectUtil.isEmpty(departSaveBean.getId()) ? depart.getId() : departSaveBean.getId());
                    }
                    if (StringUtil.notEmpty(u.getWorkCompany())) {
                        ApiBpEnterpriseInfoBean enterpriseInfo = infoMapper.findByCompanyName(u.getWorkCompany(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
                        if (enterpriseInfo == null) {
                            if (jobSync) {
                                jobService.apiDelete(bean.getId(), buildDataDto);
                            } else {
                                jobService.apiDelete(job.getId(), buildDataDto);
                            }
                            if (departSync) {
                                departService.apiDelete(departSaveBean.getId(), buildDataDto);
                            } else {
                                departService.apiDelete(depart.getId(), buildDataDto);
                            }
                            resultData.setSyncStatus(Status.ERROR_STATUS);
                            resultData.setMsg("工作单位不存在");
                            resultData.setUserCode(u.getCode());
                            result.add(resultData);
                            return;
                        }
                    }
                    try {
                        checkUserSn(u.getSn(), buildDataDto);
                    } catch (ApiException e) {
                        if (jobSync) {
                            jobService.apiDelete(bean.getId(), buildDataDto);
                        } else {
                            jobService.apiDelete(job.getId(), buildDataDto);
                        }
                        if (departSync) {
                            departService.apiDelete(departSave.getId(), buildDataDto);
                        } else {
                            departService.apiDelete(depart.getId(), buildDataDto);
                        }
                        resultData.setSyncStatus(Status.ERROR_STATUS);
                        resultData.setMsg(e.getMessage());
                        result.add(resultData);
                        return;
                    }
                    //默认帽子
                    b.setCapId(1L);
                    ApiBaseUserBean saveBean = new ApiBaseUserBean();
                    BeanUtils.copyProperties(b, saveBean);
                    saveBean.setTenentId(buildDataDto.getTenentId());
                    saveBean.setOrgCode(buildDataDto.getOrgCode());
                    apiBaseUserMapper.insert(saveBean);
//                    BaseUser save = baseUserDao.save(b);
                    if (ObjectUtil.isEmpty(bean)) {
                        updateJobUserCount(job.getId());
                    } else {
                        updateJobUserCount(bean.getId());
                    }

//                    if (forceSyncCodeAsLoginAccount) {
//                        addOrUpdateLoginAccount(b);
//                    }
                    // 新增用户添加默认角色： 员工
                    addDefaultRole4User(saveBean.getId());
                    // 同步人员
                    if (isApiEmployeeSyncOpen(buildDataDto)) {
                        locateServerService.apiSyncLocateUsers(Lists.newArrayList(saveBean), 0, buildDataDto);
                    }
                    resultData.setMsg("添加成功");
                    result.add(resultData);
                }
        );
        return result;
    }

    @Override
    @Transactional(rollbackOn = {Exception.class})
    public List<ApiResultData> batchUpdate(List<ApiBaseUserUpdateReq> data, BuildDataDto buildDataDto) {
        List<ApiResultData> result = Lists.newArrayList();
        data.forEach(u -> {
            ApiResultData resultData = new ApiResultData();
            if (StringUtil.isEmpty(u.getRealName())) {
                resultData.setSyncStatus(Status.ERROR_STATUS);
                resultData.setName(u.getRealName());
                resultData.setMsg("人员姓名不能为空");
                resultData.setUserCode(u.getCode());
                result.add(resultData);
                return;
            }
            if (StringUtil.isEmpty(u.getDepart())) {
                resultData.setSyncStatus(Status.ERROR_STATUS);
                resultData.setName(u.getRealName());
                resultData.setMsg("部门名称不能为空");
                resultData.setUserCode(u.getCode());
                result.add(resultData);
                return;
            }
            if (StringUtil.isEmpty(u.getJob())) {
                resultData.setSyncStatus(Status.ERROR_STATUS);
                resultData.setName(u.getRealName());
                resultData.setMsg("岗位名称不能为空");
                resultData.setUserCode(u.getCode());
                result.add(resultData);
                return;
            }
            if (StringUtil.isEmpty(u.getCode())) {
                resultData.setSyncStatus(Status.ERROR_STATUS);
                resultData.setName(u.getRealName());
                resultData.setMsg("工号不能为空");
                resultData.setUserCode(u.getCode());
                result.add(resultData);
                return;
            }
            if (StringUtil.isEmpty(u.getWorkCompany())) {
                resultData.setSyncStatus(Status.ERROR_STATUS);
                resultData.setName(u.getRealName());
                resultData.setMsg("工作单位不能为空");
                resultData.setUserCode(u.getCode());
                result.add(resultData);
                return;
            }
            if (ObjectUtil.isEmpty(u.getRole())) {
                resultData.setSyncStatus(Status.ERROR_STATUS);
                resultData.setName(u.getRealName());
                resultData.setMsg("身份不能为空");
                resultData.setUserCode(u.getCode());
                result.add(resultData);
                return;
            }
//            if (ObjectUtil.isEmpty(u.getSn())) {
//                resultData.setSyncStatus(Status.ERROR_STATUS);
//                resultData.setName(u.getRealName());
//                resultData.setMsg("定位卡号不能为空");
//                resultData.setUserCode(u.getCode());
//                result.add(resultData);
//                return;
//            }
            if (u.getRealName().length() > 64) {
                resultData.setSyncStatus(Status.ERROR_STATUS);
                resultData.setName(u.getRealName());
                resultData.setMsg("姓名长度不能超过64字符");
                resultData.setUserCode(u.getCode());
                result.add(resultData);
                return;
            }
            if (u.getDepart().length() > 64) {
                resultData.setSyncStatus(Status.ERROR_STATUS);
                resultData.setName(u.getRealName());
                resultData.setMsg("部门长度不能超过64字符");
                resultData.setUserCode(u.getCode());
                result.add(resultData);
                return;
            }
            if (u.getJob().length() > 64) {
                resultData.setSyncStatus(Status.ERROR_STATUS);
                resultData.setName(u.getRealName());
                resultData.setMsg("岗位长度不能超过64字符");
                result.add(resultData);
                return;
            }
            if (u.getCode().length() > 10) {
                resultData.setSyncStatus(Status.ERROR_STATUS);
                resultData.setName(u.getRealName());
                resultData.setMsg("工号长度不能超过10字符");
                resultData.setUserCode(u.getCode());
                result.add(resultData);
                return;
            }
            if (u.getWorkCompany().length() > 64) {
                resultData.setSyncStatus(Status.ERROR_STATUS);
                resultData.setName(u.getRealName());
                resultData.setMsg("工作单位长度不能超过64字符");
                resultData.setUserCode(u.getCode());
                result.add(resultData);
                return;
            }
            if (StringUtil.notEmpty(u.getSn()) && u.getSn().length() > 64) {
                resultData.setSyncStatus(Status.ERROR_STATUS);
                resultData.setName(u.getRealName());
                resultData.setMsg("定位卡号长度不能超过64字符");
                resultData.setUserCode(u.getCode());
                result.add(resultData);
                return;
            }
            resultData.setSyncStatus(Status.SUCCESS_STATUS);
            ApiBaseUserBean b = new ApiBaseUserBean();
            ApiBaseUserBean userBean = apiBaseUserMapper.findByCodeAndTenentIdAndOrgcode(u.getCode(), buildDataDto.getOrgCode(), buildDataDto.getTenentId());
            if (ObjectUtil.isEmpty(userBean)) {
                resultData.setUserCode(u.getCode());
                resultData.setSyncStatus(Status.ERROR_STATUS);
                resultData.setUserCode(u.getCode());
                resultData.setMsg("员工不存在");
                result.add(resultData);
                return;
            }
            if (StringUtil.notEmpty(u.getSn()) && apiBaseUserMapper.countBySnExcludeSelf(u.getSn(), userBean.getId(), buildDataDto.getTenentId(), buildDataDto.getOrgCode()) > 0) {
                resultData.setSyncStatus(Status.ERROR_STATUS);
                resultData.setName(u.getRealName());
                resultData.setMsg("sn已存在");
                resultData.setUserCode(u.getCode());
                result.add(resultData);
                return;
            }
            if (apiBaseUserMapper.countByNameExcludeSelf(u.getRealName(), userBean.getId(), buildDataDto.getTenentId(), buildDataDto.getOrgCode()) > 0) {
                resultData.setSyncStatus(Status.ERROR_STATUS);
                resultData.setMsg("姓名已存在");
                resultData.setUserCode(u.getCode());
                result.add(resultData);
                return;
            }
            BeanUtils.copyProperties(userBean, b);
            if (StringUtil.notEmpty(u.getRealName())) {
                b.setRealName(u.getRealName());
            }
            //更新的部门岗位没有则新建
            BpJob job = new BpJob();
//            BpJob jobSave = null;
            boolean jobSync = false;
            ApiBpJobBean jobBean;
            ApiBpJobBean jobSaveBean = new ApiBpJobBean();
            if (StringUtil.notEmpty(u.getJob())) {
                jobBean = bpJobMapper.findByNameAndCurrentCompany(u.getJob(), buildDataDto.getTenentId(), buildDataDto.getOrgCode());
                if (ObjectUtil.isEmpty(jobBean)) {
                    BpJob jobEntity = BpJob.builder().name(u.getJob()).staffCount(0).createBy(-1L).createTime(new Date())
                            .updateBy(-1L).updateTime(new Date()).uniqueId(SnowFlakeUtil.getJobId())
                            .orgCode(buildDataDto.getOrgCode()).tenentId(buildDataDto.getTenentId()).build();
                    jobSync = jobSyncService.syncApiJob(jobEntity, buildDataDto);
                    if (jobSync) {
                        jobEntity.setLocateSync(true);
                    } else {
                        jobEntity.setLocateSync(false);
                    }
                    BeanUtils.copyProperties(jobEntity, jobSaveBean);
                    bpJobMapper.insert(jobSaveBean);
//                    jobSave = jobDao.save(jobEntity);
                } else {
                    BeanUtils.copyProperties(jobBean, job);
                    jobSync = jobSyncService.syncApiJob(job, buildDataDto);
                    if (jobSync) {
                        job.setLocateSync(true);
                    } else {
                        job.setLocateSync(false);
                    }
                }
                b.setJob(ObjectUtil.isEmpty(jobSaveBean.getId()) ? job.getId() : jobSaveBean.getId());
            }
            BpDepart depart = new BpDepart();
            BpDepart departSave = null;
            boolean departSync = false;
            ApiBpDepartBean departBean = new ApiBpDepartBean();
            BpDepart fatherDepart = new BpDepart();
            if (StringUtil.notEmpty(u.getDepart())) {
                ApiBpDepartBean fatherDepartBean = bpDepartMapper.getFatherDepart(buildDataDto.getOrgCode(), buildDataDto.getTenentId());
                BeanUtils.copyProperties(fatherDepartBean, fatherDepart);

                departBean = bpDepartMapper.findFirstByNameAndCurrentCompany(u.getDepart(), buildDataDto.getOrgCode(), buildDataDto.getTenentId());
                if (ObjectUtil.isEmpty(departBean)) {
                    if (fatherDepartBean == null) {
                        //出现异常删除定位系统已保存的数据
                        if (jobSync) {
                            jobService.apiDelete(jobSaveBean.getId(), buildDataDto);
                        }
                        resultData.setSyncStatus(Status.ERROR_STATUS);
                        resultData.setMsg("顶级部门不存在");
                        resultData.setUserCode(u.getCode());
                        result.add(resultData);
                        return;
                    }
                    Integer no = fatherDepartBean.getChildNo();
                    if (no == null) {
                        no = 1;
                    }
                    BpDepart departEntity = BpDepart.builder().name(u.getDepart()).parentId(fatherDepartBean.getId())
                            .childNo(0).type(DepartType.DEPART.getId()).uniqueId(SnowFlakeUtil.getDepartId()).createBy(-1L)
                            .createTime(DateTimeUtil.date2LocalDateTime(new Date())).updateBy(-1L).updateTime(DateTimeUtil.date2LocalDateTime(new Date()))
                            .tenentId(buildDataDto.getTenentId()).orgCode(buildDataDto.getOrgCode())
                            .code(fatherDepartBean.getCode() + "-" + StringUtils.leftPad(no + "", 3, '0')).build();
                    // 调用同步接口，同步部门信息到人员在岗在位
                    departSync = departSyncService.syncApiDepart(departEntity, fatherDepart, buildDataDto);
                    if (departSync) {
                        departEntity.setLocateSync(true);
                    } else {
                        departEntity.setLocateSync(false);
                    }
                    ApiBpDepartBean departSaveEntity = new ApiBpDepartBean();
                    BeanUtils.copyProperties(departEntity, departSaveEntity);
                    bpDepartMapper.insert(departSaveEntity);
//                    departSave = departDao.save(departEntity);
                    fatherDepartBean.setChildNo(no + 1);
                    bpDepartMapper.updateById(fatherDepartBean);
//                    departDao.save(fatherDepart);
                    dataAuthService.initAllRoleDepartCache();
                    b.setDepartId(departSaveEntity.getId());
                } else {
                    //如果部门已存在也要判断定位系统中有没有，没有的话新增
                    if (fatherDepartBean == null) {
                        //出现异常删除定位系统已保存的数据
                        if (jobSync) {
                            jobService.apiDelete(jobSaveBean.getId(), buildDataDto);
                        }
                        resultData.setSyncStatus(Status.ERROR_STATUS);
                        resultData.setMsg("顶级部门不存在");
                        resultData.setUserCode(u.getCode());
                        result.add(resultData);
                        return;
                    }
                    BeanUtils.copyProperties(departBean, depart);
                    Integer no = fatherDepart.getChildNo();
                    if (no == null) {
                        no = 1;
                    }
                    // 调用同步接口，同步部门信息到人员在岗在位
                    departSync = departSyncService.syncApiDepart(depart, fatherDepart, buildDataDto);
                    if (departSync) {
                        depart.setLocateSync(true);
                    } else {
                        depart.setLocateSync(false);
                    }
                    dataAuthService.initAllRoleDepartCache();
                    b.setDepartId(depart.getId());
                }
            }
            if (ObjectUtil.isNotEmpty(u.getRole())) {
                b.setRole(u.getRole());
            }
            // 判断 定位卡 门禁卡号是否重复
            if (StringUtil.notEmpty(u.getSn())) {
                try {
                    checkUserSn(u.getSn(), buildDataDto);
                    b.setSn(u.getSn());
                } catch (ApiException e) {
                    resultData.setUserCode(u.getCode());
                    resultData.setSyncStatus(Status.ERROR_STATUS);
                    resultData.setName(b.getRealName());
                    resultData.setMsg(e.getMessage());
                    result.add(resultData);
                    return;
                }
            }
            apiBaseUserMapper.updateById(b);
//            BaseUser save = baseUserDao.save(b);

            LambdaQueryWrapper<ApiBaseLoginAccountBean> condition = new QueryWrapper<ApiBaseLoginAccountBean>().lambda()
                    .eq(ApiBaseLoginAccountBean::getUserDetailId, b.getId());
            // 账号变化或者没有账号
//            if (forceSyncCodeAsLoginAccount && baseLoginAccountMapper.selectOne(condition) == null) {
//                addOrUpdateLoginAccount(save);
//            }
            // 同步人员
//            String locateVersion = locateServerService.getLocateVersion();
//            ApiBaseConfigBean versionConfig = configMapper.findConfig(buildDataDto.getTenentId(), buildDataDto.getOrgCode(), BaseConfigCodes.LOCATE_VERSION);
//            String locateVersion = "3.x";
//            if (versionConfig != null) {
//                locateVersion = versionConfig.getValue();
//            }
            if (isApiEmployeeSyncOpen(buildDataDto)) {
//                if ("3.x".equals(locateVersion)) {
                locateServerService.apiSyncLocateUsers(Lists.newArrayList(b), 0, buildDataDto);
//                } else {
//                    locateServerService.apiSyncLocateUsers(Lists.newArrayList(b), 0, buildDataDto);
//                }
            }
            resultData.setName(b.getRealName());
            resultData.setMsg("修改成功");
            resultData.setUserCode(b.getCode());
            result.add(resultData);
            return;
        });
        return result;
    }

    @Override
    @Transactional(rollbackOn = {Exception.class})
    public List<ApiResultData> batchDelete(List<String> data, BuildDataDto buildDataDto) {
        List<ApiResultData> list = Lists.newArrayList();
        data.forEach(code -> {
            ApiResultData res = new ApiResultData();
            if (StringUtil.notEmpty(code)) {
                ApiBaseUserBean userDTO = apiBaseUserMapper.findByCodeAndTenentIdAndOrgcode(code, buildDataDto.getOrgCode(), buildDataDto.getTenentId());
                BaseUser user = new BaseUser();

                if (user == null) {
                    res.setUserCode(code);
                    res.setSyncStatus(Status.ERROR_STATUS);
                    res.setMsg("人员不存在");
                    list.add(res);
                    return;
                }
                BeanUtils.copyProperties(userDTO, user);
                user.setState(DataStateTypes.DELETE.getState());
                baseLoginAccountMapper.deleteById(userDTO.getId());
                ApiBaseUserBean saveBean = new ApiBaseUserBean();
                BeanUtils.copyProperties(user, saveBean);
//                baseLoginAccountDao.deleteByUserId(user.getId());
                apiBaseUserMapper.updateById(saveBean);
//                BaseUser save = baseUserDao.save(user);
                if (user.getJob() != null) {
                    updateJobUserCount(user.getJob());
                }
                // 同步人员
                if (isApiEmployeeSyncOpen(buildDataDto)) {
                    locateServerService.apiSyncLocateUsers(Lists.newArrayList(user), 0, buildDataDto);
                }
                res.setUserCode(code);
                res.setSyncStatus(Status.SUCCESS_STATUS);
                res.setName(saveBean.getRealName());
                res.setMsg("删除成功");
                list.add(res);
            }
        });
        return list;
    }

    @Override
    @Transactional(rollbackOn = {Exception.class})
    public List<ApiResultData> batchUpdateWorkCompany(List<ApiBaseUserUpdateWorkCompanyReq> data, BuildDataDto buildDataDto) {
        List<ApiResultData> list = Lists.newArrayList();
        String oldOrgCode = buildDataDto.getOrgCode();
        Long oldTenentId = buildDataDto.getTenentId();
        data.forEach(req -> {
            ApiResultData resultData = new ApiResultData();
            if (StringUtil.isEmpty(req.getCode())) {
                resultData.setUserCode(req.getCode());
                resultData.setSyncStatus(Status.ERROR_STATUS);
                resultData.setMsg("工号不能为空");
                list.add(resultData);
                return;
            }
            if (StringUtil.isEmpty(req.getWorkCompany())) {
                resultData.setUserCode(req.getCode());
                resultData.setSyncStatus(Status.ERROR_STATUS);
                resultData.setMsg("工作单位不能为空");
                list.add(resultData);
                return;
            }
            if (req.getCode().length() > 10) {
                resultData.setUserCode(req.getCode());
                resultData.setSyncStatus(Status.ERROR_STATUS);
                resultData.setMsg("工号长度不能超10字符");
                list.add(resultData);
                return;
            }
            if (req.getWorkCompany().length() > 64) {
                resultData.setUserCode(req.getCode());
                resultData.setSyncStatus(Status.ERROR_STATUS);
                resultData.setMsg("工作单位长度不能超64字符");
                list.add(resultData);
                return;
            }
            ApiBaseUserBean userDTO = apiBaseUserMapper.findByCodeAndTenentIdAndOrgcode(req.getCode(), buildDataDto.getOrgCode(), buildDataDto.getTenentId());
            ApiBaseUserBean newUser = new ApiBaseUserBean();

//            BaseUser user = new BaseUser();
//            BeanUtils.copyProperties(userDTO, user);
            if (userDTO == null) {
                resultData.setUserCode(req.getCode());
                resultData.setSyncStatus(Status.ERROR_STATUS);
                resultData.setMsg("人员不存在");
                list.add(resultData);
                return;
            }
            BeanUtils.copyProperties(userDTO, newUser);
            String oldUniqueId = userDTO.getUniqueId();
            //新单位
            ApiBpEnterpriseInfoBean infoBean = infoMapper.findByCompanyNameAndTenentId(req.getWorkCompany(), buildDataDto.getTenentId());
            String newOrgCode = infoBean.getOrgCode();
            Long newTenentId = infoBean.getTenentId();
            if (infoBean == null) {
                resultData.setSyncStatus(Status.ERROR_STATUS);
                resultData.setUserCode(req.getCode());
                resultData.setName(userDTO.getRealName());
                resultData.setMsg("工作单位不存在");
                list.add(resultData);
                return;
            }
            newUser.setWorkCompanyId(infoBean.getId());

            //查询第二个公司下面是否有这个人
            ApiBaseUserBean find = apiBaseUserMapper.findByCodeAndTenentIdAndOrgcode(userDTO.getCode(), newOrgCode, newTenentId);
            if (find != null) {
                resultData.setSyncStatus(Status.ERROR_STATUS);
                resultData.setMsg("已存在该工号的人员");
                resultData.setName(userDTO.getRealName());
                resultData.setUserCode(userDTO.getCode());
                list.add(resultData);
                return;
            }

            //查询新单位是否存在原单位的岗位部门，如果没有则新增
            BpJob jobSave = null;
            boolean jobSync = false;
//            Context.setTenentIdOrgCodeIntercept(false);
//            ApiToken token = apiTokenDao.findByAppId(bpEnterpriseInfo.getTenentId() + "_" + bpEnterpriseInfo.getOrgCode());
//            if (token == null) {
//                resultData.setSyncStatus(Status.ERROR_STATUS);
//                resultData.setUserCode(req.getCode());
//                resultData.setName(user.getRealName());
//                resultData.setMsg("licence配置不存在");
//                list.add(resultData);
//                return;
//            }
//            Context.setTenentIdOrgCodeIntercept(true);
//            Context.setTenentIdOrgCodeIntercept(false);
            ApiBaseConfigBean buildConfig = configMapper.findConfig(infoBean.getTenentId(), infoBean.getOrgCode(), BaseConfigCodes.LOCATE_CURRENT_BUILD_ID);
            ApiBaseConfigBean oldBuildConfig = configMapper.findConfig(userDTO.getTenentId(), userDTO.getOrgCode(), BaseConfigCodes.LOCATE_CURRENT_BUILD_ID);
//            Context.setTenentIdOrgCodeIntercept(true);
            if (buildConfig == null) {
                log.info("部门同步查询异常： 人员在岗在位buildId 未配置。");
                resultData.setSyncStatus(Status.ERROR_STATUS);
                resultData.setUserCode(req.getCode());
                resultData.setName(userDTO.getRealName());
                resultData.setMsg("人员在岗在位buildId 未配置");
                list.add(resultData);
                return;
            }
            //查询定位系统中是否存在该公司
            boolean syncCompanyFlag = departSyncService.getSyncCompany(infoBean.getTenentId(), infoBean.getOrgCode());
            BuildDataDto dto = new BuildDataDto();
            dto.setOrgCode(infoBean.getOrgCode());
            dto.setTenentId(infoBean.getTenentId());
//            Context.setTenentId(bpEnterpriseInfo.getTenentId());
//            Context.setOrgCode(bpEnterpriseInfo.getOrgCode());

            ApiBpJobBean jobBean = bpJobMapper.selectById(userDTO.getJob());
//            Optional<BpJob> jobOptional = jobDao.findById(user.getJob());
            if (jobBean != null) {
//                Context.setTenentIdOrgCodeIntercept(false);
                ApiBpJobBean newJob = bpJobMapper.findByNameAndCurrentCompany(jobBean.getName(), infoBean.getTenentId(), infoBean.getOrgCode());
//                Context.setTenentIdOrgCodeIntercept(true);
                ApiBpJobBean jobSaveEntity = new ApiBpJobBean();
                if (ObjectUtil.isEmpty(newJob)) {
//                    Context.setOrgCode(bpEnterpriseInfo.getOrgCode());
                    BpJob jobEntity = BpJob.builder().name(jobBean.getName()).staffCount(0).createBy(-1L).createTime(new Date())
                            .updateBy(-1L).updateTime(new Date()).uniqueId(SnowFlakeUtil.getJobId())
                            .orgCode(dto.getOrgCode()).tenentId(dto.getTenentId()).build();
                    if (syncCompanyFlag) {
                        jobSync = jobSyncService.syncApiJob(jobEntity, dto);
//                        jobSync = jobSyncService.syncjobCross(jobEntity, buildConfig.getValue(), infoBean.getTenentId(), infoBean.getOrgCode());
                        if (jobSync) {
                            jobEntity.setLocateSync(true);
                        } else {
                            jobEntity.setLocateSync(false);
                        }
                    }

                    BeanUtils.copyProperties(jobEntity, jobSaveEntity);
//                    Context.setOrgCode(bpEnterpriseInfo.getOrgCode());
                    bpJobMapper.insert(jobSaveEntity);
//                    jobSave = jobDao.save(jobEntity);
//                    Context.setOrgCode(oldOrgCode);
                }
                newUser.setJob(ObjectUtil.isEmpty(jobSaveEntity.getId()) ? newJob.getId() : jobSaveEntity.getId());
//                Context.setOrgCode(oldOrgCode);
            }

            ApiBpDepartBean departBean = bpDepartMapper.selectById(userDTO.getDepartId());
//            Optional<BpDepart> departOptional = departDao.findById(user.getDepartId());
            BpDepart departSave = null;
            boolean departSync = false;
            if (departBean != null) {
//                Context.setOrgCode(bpEnterpriseInfo.getOrgCode());
//                Context.setTenentIdOrgCodeIntercept(false);
                ApiBpDepartBean newDepart = bpDepartMapper.findFirstByNameAndCurrentCompany(departBean.getName(), infoBean.getOrgCode(), infoBean.getTenentId());
//                Context.setTenentIdOrgCodeIntercept(true);
                ApiBpDepartBean departSaveEntity = new ApiBpDepartBean();
                if (ObjectUtil.isEmpty(newDepart)) {
//                    Context.setTenentIdOrgCodeIntercept(false);
                    ApiBpDepartBean fatherDepartBean = bpDepartMapper.getFatherDepart(infoBean.getOrgCode(), infoBean.getTenentId());
                    BpDepart fatherDepart = new BpDepart();
                    BeanUtils.copyProperties(fatherDepartBean, fatherDepart);
//                    Context.setTenentIdOrgCodeIntercept(true);
                    if (fatherDepart == null) {
//                        if (syncCompanyFlag) {
//                            if (jobSync) {
//                                jobService.deleteCross(jobSave.getId(), buildConfig.getValue());
//                            }
//                        }
                        resultData.setSyncStatus(Status.ERROR_STATUS);
                        resultData.setMsg("顶级部门不存在");
                        resultData.setName(userDTO.getRealName());
                        resultData.setUserCode(userDTO.getCode());
                        list.add(resultData);
                        return;
                    }
                    Integer no = fatherDepartBean.getChildNo();
                    if (no == null) {
                        no = 1;
                    }
                    BpDepart departEntity = BpDepart.builder().name(departBean.getName()).parentId(fatherDepart.getId())
                            .childNo(0).type(DepartType.DEPART.getId()).uniqueId(SnowFlakeUtil.getDepartId()).createBy(-1L)
                            .createTime(DateTimeUtil.date2LocalDateTime(new Date())).updateBy(-1L).updateTime(DateTimeUtil.date2LocalDateTime(new Date()))
                            .tenentId(infoBean.getTenentId()).orgCode(infoBean.getOrgCode())
                            .code(fatherDepart.getCode() + "-" + StringUtils.leftPad(no + "", 3, '0')).build();
                    // 调用同步接口，同步部门信息到人员在岗在位
                    if (syncCompanyFlag) {
                        departSync = departSyncService.syncApiDepart(departEntity, fatherDepart, dto);
//                        departSync = departSyncService.syncDepartCross(departEntity, fatherDepart, buildConfig.getValue());
                        if (departSync) {
                            departEntity.setLocateSync(true);
                        } else {
                            departEntity.setLocateSync(false);
                        }
                    }

                    BeanUtils.copyProperties(departEntity, departSaveEntity);
                    //                    Context.setOrgCode(bpEnterpriseInfo.getOrgCode());
                    bpDepartMapper.insert(departSaveEntity);
//                    departSave = departDao.save(departEntity);
                    fatherDepartBean.setChildNo(no + 1);
                    bpDepartMapper.updateById(fatherDepartBean);
//                    departDao.save(fatherDepart);
//                    Context.setOrgCode(oldOrgCode);
                    dataAuthService.initAllRoleDepartCache();
                }
                newUser.setDepartId(ObjectUtil.isEmpty(departSaveEntity.getId()) ? newDepart.getId() : departSaveEntity.getId());
//                Context.setOrgCode(oldOrgCode);
            }
            newUser.setOrgCode(infoBean.getOrgCode());
            //换新的uniqueId
            newUser.setUniqueId(SnowFlakeUtil.getUserId());
            if (StringUtil.notEmpty(userDTO.getSn())) {
                checkUserSn(userDTO.getSn(), dto);
            }
            //在新公司新增人员
            apiBaseUserMapper.insert(newUser);
            //新增成功将原来的人员删除
//            userDTO.setState(44);
            apiBaseUserMapper.updateUserState(userDTO.getId());
//            userDTO.setState(1);
            BaseUser save = new BaseUser();
            BeanUtils.copyProperties(newUser, save);
            save.setOrgCode(newOrgCode);
            save.setTenentId(newTenentId);
            save.setId(null);
//            BaseUser save = baseUserDao.save(user);
            LambdaQueryWrapper<ApiBaseLoginAccountBean> condition = new QueryWrapper<ApiBaseLoginAccountBean>().lambda()
                    .eq(ApiBaseLoginAccountBean::getUserDetailId, save.getId());
            // 账号变化或者没有账号
            if (forceSyncCodeAsLoginAccount && baseLoginAccountMapper.selectOne(condition) == null) {
//                addOrUpdateLoginAccountV2(save, infoBean);
            }
            String locateVersion = locateServerService.getLocateVersion();
            // 同步人员
            if (syncCompanyFlag) {
                if (isApiEmployeeSyncOpen(buildDataDto)) {
                    if (StringUtil.notEmpty(locateVersion) && ("3.x".equals(locateVersion) || "4.x".equals(locateVersion))) {
//                        ApiToken oldToken = apiTokenDao.findByAppId(user.getTenentId() + "_" + user.getOrgCode());
//                        locateServerService.apiSyncLocateUsers(Lists.newArrayList(save), 0, dto);
                        locateServerService.syncLocateUsers(Lists.newArrayList(save), newTenentId, newOrgCode, oldOrgCode, oldTenentId, oldUniqueId, oldBuildConfig.getValue(), buildConfig.getValue());
                    }
                }
            }
            resultData.setName(save.getRealName());
            resultData.setMsg("修改成功");
            resultData.setSyncStatus(Status.SUCCESS_STATUS);
            resultData.setUserCode(save.getCode());
            list.add(resultData);
            return;
        });
        return list;
    }

    private void checkUser(String sn) {
        List<BpContractorStaff> staffSn = new ArrayList<>();
        List<BaseUser> userSn = new ArrayList<>();
        if (StringUtils.isNotBlank(sn)) {
            staffSn = bpContractorStaffDao.findBySnAndState(sn, 1);
            userSn = baseUserDao.findBySn(sn);
        }
        if (!CollectionUtils.isEmpty(staffSn) && staffSn.size() > 0) {
            throw new ApiException(Status.API_SN_USED_BY_CONTRACTOR);
        }
        if (!CollectionUtils.isEmpty(userSn) && userSn.size() > 1) {
            throw new ApiException(Status.API_SN_USED_BY_USER);
        }
    }

    private boolean isEmployeeSyncOpen() {
        BaseConfig config = baseConfigService.findFirstConfig(BaseConfigCodes.LOCATE_SERVER_EMPLOYEE_SYNC_OPEN);
        return config == null ? false : "true".equalsIgnoreCase(config.getValue());
    }

    private boolean isApiEmployeeSyncOpen(BuildDataDto dto) {
        ApiBaseConfigBean config = configMapper.findConfig(dto.getTenentId(), dto.getOrgCode(), BaseConfigCodes.LOCATE_SERVER_EMPLOYEE_SYNC_OPEN);
        return config == null ? false : "true".equalsIgnoreCase(config.getValue());
    }

    // 每个新增用户添加默认角色： 员工
    private void addDefaultRole4User(Long userId) {
        BaseRole baseRole = baseRoleDao.findFirstByName(Constants.USER_DEFAULT_ROLE_NAME);
        if (baseRole != null) {
            BaseRoleUserLoginRole userRole = new BaseRoleUserLoginRole();
            userRole.setUserId(userId);
            userRole.setRoleId(baseRole.getId());
            baseRoleUserLoginRoleDao.save(userRole);
        }

    }

    private void addOrUpdateLoginAccount(BaseUser save) {
        baseLoginAccountService.addOrUpdateLoginAccount(save, save.getCode(), defaultPassword);
    }

    private void addOrUpdateLoginAccountV2(BaseUser save, BpEnterpriseInfo info) {
        baseLoginAccountService.addOrUpdateLoginAccountV2(save, save.getCode(), defaultPassword, info);
    }

    /**
     * @param jobId
     */
    protected void updateJobUserCount(Long jobId) {
        jobDao.updateJobUserCount(jobId);
    }

    private void checkUserSn(String sn, BuildDataDto dto) {
        List<ApiBpContractorStaffBean> contractorStaffBeanList = new ArrayList<>();
        List<ApiBaseUserBean> userBeanList = new ArrayList<>();
        if (StringUtils.isNotBlank(sn)) {
            contractorStaffBeanList = contractorStaffMapper.findBySnAndState(sn, 1, dto.getTenentId(), dto.getOrgCode());
//            staffSn = bpContractorStaffDao.findBySnAndState(sn, 1);
            userBeanList = apiBaseUserMapper.findBySn(sn, dto.getTenentId(), dto.getOrgCode());
//            userSn = baseUserDao.findBySn(sn);
            if (!CollectionUtils.isEmpty(contractorStaffBeanList) && contractorStaffBeanList.size() > 0) {
                throw new ApiException(Status.API_SN_USED_BY_CONTRACTOR);
            }
            if (!CollectionUtils.isEmpty(userBeanList) && userBeanList.size() > 1) {
                throw new ApiException(Status.API_SN_USED_BY_USER);
            }
        }
    }
}
